package com.henu.acmrating.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.henu.acmrating.common.Result;
import com.henu.acmrating.pojo.Blog;
import com.henu.acmrating.pojo.ChildComment;
import com.henu.acmrating.pojo.Comment;
import com.henu.acmrating.pojo.User;
import com.henu.acmrating.service.BlogService;
import com.henu.acmrating.service.ChildCommentService;
import com.henu.acmrating.service.CommentService;
import com.henu.acmrating.service.UserService;
import com.henu.acmrating.utils.JwtUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@RestController
@RequestMapping("/api")
public class CommentController {

    @Resource
    CommentService commentService;

    @Resource
    ChildCommentService childCommentService;

    @Resource
    UserService userService;

    @Resource
    BlogService blogService;

    /**
     * 回复博客信息
     */
    @RequestMapping(value = "/sendMessage", method = RequestMethod.POST)
    public Result sendMessage(@RequestBody Comment comment, HttpServletRequest request) {
        // 1.检测内容和博客id 是否为空
        if (comment.getContent() == null || comment.getBlogId() == null)
            return Result.error("发送失败");

        // 2.拿到userId
        Integer userId = JwtUtils.getUserId(request);
        comment.setUserId(userId);
        comment.setCreateDate(JwtUtils.getDate());

        // 3.保存数据库
        commentService.insert(comment);

        return Result.success("发送成功");
    }

    /**
     * 子消息（回复消息
     */
    @RequestMapping(value = "/sendChildMessage", method = RequestMethod.POST)
    public Result sendChildMessage(@RequestBody ChildComment childComment, HttpServletRequest request) {
        // 1.检测内容和博客id 是否为空
        if (childComment.getContent() == null || childComment.getCommentId() == null ||
                childComment.getTargetId() == null) {
            return Result.error("回复失败");
        }
        // 2.拿到userId
        Integer userId = JwtUtils.getUserId(request);
        childComment.setUserId(userId);
        childComment.setCreateDate(JwtUtils.getDate());
        // 3.保存数据库
        childCommentService.insert(childComment);

        return Result.success("回复成功");
    }

    @RequestMapping(value = "/getComments", method = RequestMethod.POST)
    public Result getComments(@RequestBody JSONObject jsonObject) {
        Integer blogId = jsonObject.getInteger("id");
        List<Comment> comments = commentService.selectByBlogId(blogId);

        // 记录评论个数
        AtomicInteger count = new AtomicInteger();

        // 0. 查询所有评论
        LinkedList<Object> commentList = new LinkedList<>();


        // 1.遍历comment
        comments.forEach(comment -> {
            // 1.1 把comment对象转字符串在放进JSONObject
            JSONObject commentJson = JSONObject.parseObject(JSON.toJSONString(comment));
            commentJson.put("commentUser", userService.selectByPrimaryKey(comment.getUserId()));

            // 1.2. 查询子评论
            List<ChildComment> childComments = childCommentService.selectByCommentId(comment.getId());

            LinkedList<Object> childList = new LinkedList<>();


            childComments.forEach(child -> {
                // 1.3 把child对象放进jsonObject
                JSONObject childJson = JSONObject.parseObject(JSON.toJSONString(child));
                childJson.put("commentUser", userService.selectByPrimaryKey(child.getUserId()));
                childJson.put("targetUser", userService.selectByPrimaryKey(child.getTargetId()));

                // 1.4 封装好的子评价放进 list
                childList.add(childJson);
            });
            count.addAndGet(childList.size());
            // 1.5 封装子评价list
            commentJson.put("childrenList", childList);

            // 1.6. 封装好的评论放进list
            commentList.add(commentJson);
        });
        count.addAndGet(commentList.size());

        // 2.封装最终数据
        JSONObject json = new JSONObject();

        Blog blog = blogService.selectByPrimaryKey(blogId);
        User user = userService.selectByPrimaryKey(blog.getUserId());
        json.put("authorId", user.getUserId());
        json.put("userImage", user.getUserImage());
        // 3.封装评价个数
        json.put("commentNum", count);
        json.put("commentList", commentList);

        return Result.success(json);
    }

}
